#include "file_sun.h"
#include <string.h>

static char *fileType = ".dat";

#define DEBUG_FILENEW 0
/**
 * @brief fileNew
 * @param dir :demo --const char *CDIR = "E:\\myfile\\";
 * @param fileName :字母下划线
 * @return 0 ok; 1 err;
 */
uint8_t fileNew(char *dir, char *fileName, FILE **pFile)
{
    char temp[50];
    FILE *file = NULL;

    memset(temp, 0, sizeof(temp));
    strcpy(temp, dir);
    strcpy(temp + strlen(dir), fileName);
    strcpy(temp + strlen(dir) + strlen(fileName), fileType);
#if DEBUG_FILENEW
    printf(temp);
#endif
    //    file = fopen("hello.txt", "w");
    file = fopen(temp, "a");
    if(file == NULL) {
#if DEBUG_FILENEW
        printf("file %u pFile %u\r\n", file, pFile);
#endif
        return 1;
    } else {
        *pFile = file;
#if DEBUG_FILENEW
        printf("file %u pFile %u\r\n", file, *pFile);
#endif
        return 0;
    }
}

#define DEBUG_FILEWRITE 0

void flush(FILE* stream)
{
    int duphandle;
    /*flushthestream'sinternalbuffer*/
    fflush(stream);
    /*makeaduplicatefilehandle*/
    duphandle=dup(fileno(stream));
    /*closetheduplicatehandletoflushtheDOSbuffer*/
    close(duphandle);
}


/**
 * @brief fileWrite
 * @param dir
 * @param fileName
 * @param pDat
 * @param datLen
 * @return  0 ok; 1 err;
 */
uint8_t fileWrite(FILE *pFile, char *pDat, uint16_t datLen)
{
    uint8_t ret = 0;
    if(pFile == NULL) return 1;

    ret = fwrite(pDat, datLen , 1, pFile );
    flush(pFile);
#if DEBUG_FILEWRITE
    printf("fileWrite %d\r\n", ret);
#endif

    return 0;
}

uint8_t fileClose(FILE *pFile)
{
    fclose(pFile);
}
